package dao;

import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MainMessageDao {
    Util util = new Util();
    Connection con = null;

    public void addMessage(String name, String message, int status) {
        con = util.getConnection();
        String sql = "insert into main_message(name,message,status) values(?,?,?)";
        try {
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, message);
            preparedStatement.setInt(3, status);
            preparedStatement.execute();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String[] getMessages() {
        con = util.getConnection();
        List<String> messageList = new ArrayList<>();
        String sql = "select * from main_message";
        try {
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String string1 = resultSet.getString("message");
                String string2 = resultSet.getString("name");
                int status = resultSet.getInt("status");
                String string = string2 + ":" + string1 + ":" + status;
                messageList.add(string);
            }
            String[] usersArray = new String[messageList.size()];
            usersArray = messageList.toArray(usersArray);
            return usersArray;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}